//
//  CalendarView.m
//  XieHe
//
//  Created by 孙璐 on 17/4/17.
//  Copyright © 2017年 孙璐. All rights reserved.
//
#import "SZCalendarCell.h"
#import "AFNetworking/AFNetworking.h"
#define URLS @"http://www.dynaflowtest.cn/Handler/OrderHandler.ashx?"
#import "CalendarView.h"
#define UISCREEN_WIDTH ([[UIScreen mainScreen]bounds].size.width)
#define UISCREEN_HEIGHT ([[UIScreen mainScreen]bounds].size.height)
//文字大小
#define kScreenWidthRatio  (UISCREEN_WIDTH / 375)
#define kScreenHeightRatio (UISCREEN_HEIGHT / 667)
#define AdaptedWidthValue(x)  (ceilf((x) * kScreenWidthRatio))
#define AdaptedHeightValue(x) (ceilf((x) * kScreenHeightRatio))
#define SystemFontWithSize(R)     [UIFont systemFontOfSize:(AdaptedWidthValue(R))]
#define SystemFontWithWeightSize(R)      [UIFont systemFontOfSize:(AdaptedWidthValue(R)) weight:1]
@implementation CalendarView
-(instancetype)initWithFrame:(CGRect)frame AndDate:(NSDate *)today AndOtherDate:(NSDate *)date AndDeviceDetailInfoCode:(NSString *)deviceDetailInfoCode{
    self = [super initWithFrame:frame];
    if (self != nil) {
        self.today = today;
        self.date = date;
        self.deviceDetailInfoCode = deviceDetailInfoCode;
        [self createSub];
        self.arrDay = [[NSMutableArray alloc]init];
        
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        //默认当前选中当天
        self.nowChooseDay =[formatter stringFromDate:date];
        [self loadData];
    }
    return self;
}
-(void)createSub{
    UIButton * btnLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    btnLeft.frame = CGRectMake(10*kScreenWidthRatio, 0, 75*kScreenWidthRatio, 20*kScreenHeightRatio);
    [btnLeft setBackgroundImage:[UIImage imageNamed:@"左"] forState:UIControlStateNormal];
    [btnLeft addTarget:self action:@selector(btnLeftPress) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btnLeft];
    
    UIButton * btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRight setBackgroundImage:[UIImage imageNamed:@"右"] forState:UIControlStateNormal];
    [btnRight addTarget:self action:@selector(btnRightPress) forControlEvents:UIControlEventTouchUpInside];
    btnRight.frame = CGRectMake(self.frame.size.width-85*kScreenWidthRatio, 0, 75*kScreenWidthRatio, 20*kScreenHeightRatio);
    [self addSubview:btnRight];
    
    self.labelCalenderTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20*kScreenHeightRatio)];
    [self.labelCalenderTitle setTextColor:[UIColor blackColor]];
    [self.labelCalenderTitle setFont:SystemFontWithSize(17)];
    [self.labelCalenderTitle setTextAlignment:NSTextAlignmentCenter];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    [self.labelCalenderTitle setText:[dateFormatter stringFromDate:self.date]];
    [self addSubview:self.labelCalenderTitle];
    
    self.weekArr = @[@"Su",@"Mo",@"Tu",@"We",@"Th",@"Fi",@"Sa"];
    UICollectionViewFlowLayout *layout=[[ UICollectionViewFlowLayout alloc ] init ];
    self.collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0,30*kScreenHeightRatio,self.frame.size.width,213*kScreenHeightRatio) collectionViewLayout:layout];
    self.collectionV. backgroundColor =[ UIColor whiteColor ];
    self.collectionV.delegate = self;
    self.collectionV.dataSource = self;
    [self.collectionV registerClass:[SZCalendarCell class] forCellWithReuseIdentifier:@"COLLECTION_CELL"];
    self.collectionV.showsVerticalScrollIndicator = NO;
    layout.itemSize = CGSizeMake(self.collectionV.frame.size.width/7, self.collectionV.frame.size.height/7);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    [self addSubview:self.collectionV];
}
-(void)btnLeftPress{
    self.date = [self lastMonth:self.date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    [self.labelCalenderTitle setText:[dateFormatter stringFromDate:self.date]];
    [self loadData];

    self.nowChooseDay = [NSString stringWithFormat:@"%@-%@",[dateFormatter stringFromDate:self.date],[self.nowChooseDay substringFromIndex:self.nowChooseDay.length-2]];
    self.refresh(self.nowChooseDay);
    
    
}
-(void)btnRightPress{
    self.date = [self nextMonth:self.date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM"];
    [self.labelCalenderTitle setText:[dateFormatter stringFromDate:self.date]];
    [self loadData];
    self.nowChooseDay = [NSString stringWithFormat:@"%@-%@",[dateFormatter stringFromDate:self.date ],[self.nowChooseDay substringFromIndex:self.nowChooseDay.length-2]];
    self.refresh(self.nowChooseDay);

}

- (NSDate *)lastMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = -1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}

- (NSDate*)nextMonth:(NSDate *)date{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.month = +1;
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];
    return newDate;
}
-(void)loadData{
    self.arrData = [[NSMutableArray alloc]init];
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    dic[@"table"]=@"GetOneMonthOrderPercent";
    dic[@"DeviceDetailInfoCode"]=self.deviceDetailInfoCode;
    dic[@"Month"]=self.date;
    [manager GET:URLS parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray * jsonArr = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        if (jsonArr != nil) {
            for (NSDictionary * dic in jsonArr) {
                [self.arrData addObject:dic[@"Count"]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.arrDay removeAllObjects];
                [self.collectionV reloadData];
            });
            NSLog(@"%lu",(unsigned long)self.arrData.count);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误：%@",error);
    }];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return self.weekArr.count;
    } else {
        return 42;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SZCalendarCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"COLLECTION_CELL" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        [cell.dateLabel setText:self.weekArr[indexPath.row]];
        [cell.dateLabel setTextColor:[UIColor blackColor]];
        [cell.dateLabel setFont:SystemFontWithSize(9)];
        [cell.dateLabel setBackgroundColor:[UIColor whiteColor]];
        cell.progress.hidden = YES;
    } else {
        NSInteger daysInThisMonth = [self totaldaysInMonth:_date];
        NSInteger firstWeekday = [self firstWeekdayInThisMonth:_date];
        
        NSInteger day = 0;
        NSInteger i = indexPath.row;
        
        if (i < firstWeekday) {
            [cell.dateLabel setText:@""];
            cell.progress.hidden = YES;
            [cell.dateLabel setFont:SystemFontWithSize(14)];
            [cell.dateLabel setBackgroundColor:[UIColor clearColor]];
            cell.dateLabel.layer.cornerRadius = 0;
            cell.dateLabel.clipsToBounds = YES;
            
        }else if (i > firstWeekday + daysInThisMonth - 1){
            [cell.dateLabel setText:@""];
            cell.progress.hidden = YES;
            [cell.dateLabel setFont:SystemFontWithSize(14)];
            [cell.dateLabel setBackgroundColor:[UIColor clearColor]];
            cell.dateLabel.layer.cornerRadius = 0;
            cell.dateLabel.clipsToBounds = YES;
        }else{
            day = i - firstWeekday + 1;
            [cell.dateLabel setText:[NSString stringWithFormat:@"%li",(long)day]];
           [cell.dateLabel setTextColor:[UIColor colorWithRed:141/255.0 green:153/255.0 blue:166/255.0 alpha:1]];
            [cell.dateLabel setFont:SystemFontWithSize(14)];
            [cell.dateLabel setBackgroundColor:[UIColor clearColor]];
            cell.dateLabel.layer.cornerRadius = 0;
            cell.dateLabel.clipsToBounds = YES;
            
            cell.progress.hidden = NO;
            if (self.arrData.count != 0) {
                NSNumber * num = self.arrData[day-1];
                cell.progress.progress = [num doubleValue]/(double)10;
            }
//            //this month
//            if ([_today compare:_date] == NSOrderedSame) {
//                if (day == [self day:_date]) {
//                    [cell.dateLabel setTextColor:[UIColor whiteColor]];
//                    [cell.dateLabel setBackgroundColor:[UIColor colorWithRed:60/255.0 green:186/255.0 blue:146/255.0 alpha:1]];
//                    cell.dateLabel.layer.cornerRadius = 20*kScreenHeightRatio/2;
//                    cell.dateLabel.clipsToBounds = YES;
//                } else if (day > [self day:_date]) {
//                    [cell.dateLabel setTextColor:[UIColor colorWithRed:141/255.0 green:153/255.0 blue:166/255.0 alpha:1]];
//                }
//            } else if ([_today compare:_date] == NSOrderedAscending) {
//                [cell.dateLabel setTextColor:[UIColor grayColor]];
//            }
            [cell.dateLabel setTextColor:[UIColor colorWithRed:141/255.0 green:153/255.0 blue:166/255.0 alpha:1]];
            if ([[self.nowChooseDay substringFromIndex:self.nowChooseDay.length-2] integerValue] == [cell.dateLabel.text integerValue]) {
                [cell.dateLabel setTextColor:[UIColor whiteColor]];
                    [cell.dateLabel setBackgroundColor:[UIColor colorWithRed:60/255.0 green:186/255.0 blue:146/255.0 alpha:1]];
                    cell.dateLabel.layer.cornerRadius = 20*kScreenHeightRatio/2;
                    cell.dateLabel.clipsToBounds = YES;
            }
        }
        [self.arrDay addObject:cell.dateLabel.text];
    }
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (![self.arrDay[indexPath.row] isEqualToString:@""]) {
        if ([self.arrDay[indexPath.row] integerValue] < 10) {
            self.nowChooseDay = [NSString stringWithFormat:@"%@-0%@",self.labelCalenderTitle.text,self.arrDay[indexPath.row]];
        }
        else{
            self.nowChooseDay = [NSString stringWithFormat:@"%@-%@",self.labelCalenderTitle.text,self.arrDay[indexPath.row]];
        }
        self.refresh(self.nowChooseDay);
        [self.collectionV reloadData];
    }
}
- (NSInteger)day:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components day];
}


- (NSInteger)month:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components month];
}

- (NSInteger)year:(NSDate *)date{
    NSDateComponents *components = [[NSCalendar currentCalendar] components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    return [components year];
}
- (NSInteger)firstWeekdayInThisMonth:(NSDate *)date{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar setFirstWeekday:1];//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
    NSDateComponents *comp = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:date];
    [comp setDay:1];
    NSDate *firstDayOfMonthDate = [calendar dateFromComponents:comp];
    
    NSUInteger firstWeekday = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekOfMonth forDate:firstDayOfMonthDate];
    return firstWeekday - 1;
}
- (NSInteger)totaldaysInMonth:(NSDate *)date{
    NSRange daysInLastMonth = [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    return daysInLastMonth.length;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
 }
*/

@end
